package com.java80.littlegame.common.base.vertx;

import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.java80.littlegame.common.base.data.GameUser;
import com.java80.littlegame.common.msg.BaseMsg;

import io.vertx.core.AbstractVerticle;

public class VertxMessageHelper extends AbstractVerticle {
	private static VertxMessageHelper instance = null;
	final transient static Logger log = LoggerFactory.getLogger(VertxMessageHelper.class);

	@Override
	public void start() throws Exception {
		super.start();
		instance = this;
	}

	public static void sendMessageToService(String queue, String msg) {
		log.info("发送消息到集群，队列：{}，消息：{}", queue, msg);
		try {
			// instance.vertx.eventBus().publish(queue, msg);
			instance.vertx.eventBus().send(queue, msg, rf -> {
				if (rf.succeeded()) {

				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void sendMessageToGateWay(GameUser user, BaseMsg msg) {
		if (user == null) {
			log.info("当前GameUser为null");
			return;
		}
		ServiceStatus serviceStatus = ServiceStatusHelper.findServiceStatus(user.getGatewayServiceId());
		sendMessageToService(serviceStatus.getServiceQueueName(), msg.toString());
	}

	public static void broadcastMessageToAllService(BaseMsg msg) {
		Collection<ServiceStatus> findServiceStatus = ServiceStatusHelper.getAllServiceStatus().values();
		for (ServiceStatus serviceStatus : findServiceStatus) {
			VertxMessageHelper.sendMessageToService(serviceStatus.getServiceQueueName(), msg.toString());
		}
	}

	public static void broadcastMessageToService(int serviceType, BaseMsg msg) {
		List<ServiceStatus> findServiceStatus = ServiceStatusHelper.findServiceStatus(serviceType);
		for (ServiceStatus serviceStatus : findServiceStatus) {
			VertxMessageHelper.sendMessageToService(serviceStatus.getServiceQueueName(), msg.toString());
		}
	}

}
